//
//  SCAOnboardingView.m
//  Staff
//
//  Created by caiyao on 2/2/15.
//
//

#import "SCAOnboardingView.h"
#import "OnboardingViewController.h"

@implementation SCAOnboardingView

- (id)initWithFrame:(CGRect) frame images:(NSArray *)images {
    if (self = [super initWithFrame:frame]) {
        
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.backgroundColor = [UIColor grayColor];
        _scrollView.contentSize = CGSizeMake(self.bounds.size.width*[images count], self.bounds.size.height);
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        for (int i = 0; i < [images count]; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*_scrollView.bounds.size.width, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)];
            imageView.backgroundColor = [UIColor yellowColor];
            imageView.image = [UIImage imageNamed:[images objectAtIndex:i]];
            [_scrollView addSubview:imageView];
        }
        [self addSubview:_scrollView];
        
        _pageControl = [[SCAPageControl alloc] initWithFrame:CGRectMake(0, 40, self.bounds.size.width, 69)];
        _pageControl.delegate = self;
        _pageControl.numberOfPages = [images count];
        [self addSubview:_pageControl];
        
        UITapGestureRecognizer *tapR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
        [self addGestureRecognizer:tapR];
    }
    
    return self;
}

- (void)handleTap {
    if (_scrollView.contentOffset.x/_scrollView.bounds.size.width == _scrollView.contentSize.width/_scrollView.bounds.size.width-1) {
        [_onboardingViewController showGreenLaisee];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    _pageControl.currentPage = page;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)selectedPageAtIndex:(NSInteger)index {
    [_scrollView setContentOffset:CGPointMake(index*_scrollView.bounds.size.width, 0) animated:YES];
    _pageControl.currentPage = index;
}

@end
